#!/bin/bash

# 定义域名和邮箱
DOMAIN="999.sa"  # 替换为你的域名
EMAIL="rolandmusaje74@gmail.com"

# 输出颜色定义
GREEN='\033[0;32m':wq
RED='\033[0;31m'
NC='\033[0m' # No Color

# 修复 hosts 文件函数
fix_hosts() {
    echo -e "${GREEN}检查并修复 hosts 文件...${NC}"
    HOSTNAME=$(hostname)
    if ! grep -q "127.0.0.1 $HOSTNAME" /etc/hosts; then
        sudo cp /etc/hosts /etc/hosts.backup
        echo "127.0.0.1 $HOSTNAME" | sudo tee -a /etc/hosts
    fi
}

# 修复 nginx pid 文件
fix_nginx_pid() {
    echo -e "${GREEN}修复 nginx pid 文件...${NC}"
    sudo mkdir -p /run/nginx
    sudo nginx -t  # 测试配置
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}Nginx 配置正确${NC}"
    else
        echo -e "${RED}Nginx 配置错误${NC}"
        exit 1
    fi
}

# 重新加载 nginx
reload_nginx() {
    echo -e "${GREEN}重新加载 Nginx...${NC}"
    sudo nginx -s reload || sudo systemctl reload nginx
}

# 安全停止 nginx
stop_nginx() {
    echo -e "${GREEN}停止 Nginx...${NC}"
    sudo nginx -s quit || sudo systemctl stop nginx
    # 确保 nginx 完全停止
    sudo pkill nginx
    sleep 2
}

# 启动 nginx
start_nginx() {
    echo -e "${GREEN}启动 Nginx...${NC}"
    sudo systemctl start nginx || sudo nginx
    sleep 2
}

echo -e "${GREEN}开始安装 SSL 证书...${NC}"

# 1. 修复 hosts 文件
fix_hosts

# 2. 更新系统包
echo -e "${GREEN}更新系统包...${NC}"
sudo apt update

# 3. 安装 certbot
echo -e "${GREEN}安装 certbot...${NC}"
sudo apt install -y certbot python3-certbot-nginx

# 4. 修复和重启 nginx
fix_nginx_pid
stop_nginx
start_nginx

# 5. 安装证书
echo -e "${GREEN}开始安装证书...${NC}"
sudo certbot --nginx \
  -d $DOMAIN \
  --email $EMAIL \
  --agree-tos \
  --non-interactive \
  --no-redirect

# 检查证书安装结果
if [ $? -ne 0 ]; then
    echo -e "${RED}证书安装失败！${NC}"
    exit 1
fi

# 6. 重启 nginx
stop_nginx
start_nginx

# 7. 检查 nginx 状态
echo -e "${GREEN}检查 nginx 状态...${NC}"
sudo systemctl status nginx

echo -e "${GREEN}证书安装完成！${NC}"

# 显示证书信息
echo -e "${GREEN}证书信息：${NC}"
sudo certbot certificates